﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using TFSCommon.Datasets;

namespace TFSCommon
{
    public partial class BugSelection : Form, Common.Forms.IBugSelection
    {
        private TFSProvider m_tfsp = null;

        public BugSelection(String parameters)
        {
            InitializeComponent();
            m_tfsp = new TFSProvider(new Settings.MySettingsManager(parameters));
        }

        public String BugId
        {
            get
            {
                string result = string.Empty;

                foreach (DataGridViewRow row in dataWorkItem.SelectedRows)
                {
                    if (!string.IsNullOrEmpty(result))
                    {
                        result += ", ";
                    }

                    result += row.Cells[idDataGridViewTextBoxColumn.Name].Value.ToString();
                }

                return result;
            }
        }

        public String Summary
        {
            get
            {
                string result = string.Empty;

                foreach (DataGridViewRow row in dataWorkItem.SelectedRows)
                {
                    if (!string.IsNullOrEmpty(result))
                    {
                        result += Environment.NewLine;
                    }

                    result += row.Cells[titleDataGridViewTextBoxColumn.Name].Value.ToString();
                }

                return result;
            }
        }

        public String Message
        {
            get { return string.Format("-----{2}BugID : {0}{2}{2}{1}", BugId, Summary, Environment.NewLine); }
        }

        public bool AddCheckIn(string source_base_path, string note, string revision, string[] filelist)
        {
            List<int> ids = new List<int>();

            foreach (DataGridViewRow row in dataWorkItem.SelectedRows)
            {
                MyWorkItem wi = (workItemBindingSource[row.Index] as MyWorkItem);

                if (wi.IsDirty)
                    wi.Save();
                
                ids.Add(int.Parse(row.Cells[idDataGridViewTextBoxColumn.Name].Value.ToString()));
            }

            string description = string.Empty;

            if (!string.IsNullOrEmpty(source_base_path))
                description += string.Format("Base path : {0}{1}", source_base_path, Environment.NewLine);

            if (filelist.Length > 0)
            {
                description += "-----Files list-----";

                foreach (string s in filelist)
                    description += Environment.NewLine + s;
            }

            return m_tfsp.AddCommit(ids.ToArray(), revision, note, description);
        }

        #region Filter Expansion
        private bool FilterExpanded
        {
            get { return filter_expanded_; }
            set
            {
                if (value)
                {
                    ExpandFilter();
                }
                else
                {
                    CollapseFilter();
                }
            }
        }

        private bool filter_expanded_ = true;

        private void pictExpandFilter_Click(object sender, EventArgs e)
        {
            FilterExpanded = !FilterExpanded;
        }

        private int CalculateHeight(Control container)
        {
            int result = 11;

            foreach (Control control in container.Controls)
            {
                if (control.Visible)
                    result = Math.Max(result, control.Bottom);
            }

            return result + 6;
        }

        private void ExpandFilter()
        {
            filter_expanded_ = true;
            pictExpandFilter.Image = Common.Resources.CommonResources.ImageSectionOpened;

            grpFilter.Height = CalculateHeight(grpFilter);
            grpFilter.Enabled = true;

            UpdateFilterLinkedPosition();
        }

        private void CollapseFilter()
        {
            filter_expanded_ = false;
            pictExpandFilter.Image = Common.Resources.CommonResources.ImageSectionClosed;

            grpFilter.Height = 17;
            grpFilter.Enabled = false;

            UpdateFilterLinkedPosition();
        }

        private void UpdateFilterLinkedPosition()
        {
            int delta = grpFilter.Bottom + 6 - dataWorkItem.Top;
            dataWorkItem.Height -= delta;
            dataWorkItem.Top += delta;
        }
        #endregion Filter Expansion

        private void BugSelection_Load(object sender, EventArgs e)
        {
            try
            {
                m_tfsp.Connect();
            }
            catch
            {
                MessageBox.Show("Unable to connect to TFS Server");
                this.Close();
            }
        }

        private void BugSelection_Shown(object sender, EventArgs e)
        {
            if (stateDataGridViewTextBoxColumn.Items.Count == 0)
            {
                stateDataGridViewTextBoxColumn.Items.Clear();
                stateDataGridViewTextBoxColumn.Items.AddRange(m_tfsp.GetFieldValues("Task", "State", false).ToArray());

                ExpandFilter();
                chkCustomQuery_CheckedChanged(chkCustomQuery, new EventArgs());

                cboFilterStoredQuery.Items.AddRange(m_tfsp.GetQueries().ToArray());

                if (cboFilterStoredQuery.Items.Count > 0)
                {
                    cboFilterStoredQuery.SelectedIndex = 0;
                }
            }
        }

        private void cboFilterQuery_SelectedIndexChanged(object sender, EventArgs e)
        {
            workItemBindingSource.Clear();

            if (null != cboFilterStoredQuery.SelectedItem)
            {
                WorkItemCollection items = m_tfsp.GetWorkItems(cboFilterStoredQuery.SelectedItem as QueryDefinition);

                foreach (WorkItem item in items)
                {
                    workItemBindingSource.Add(new MyWorkItem(item));
                }
            }
        }

        private void dataWorkItem_SelectionChanged(object sender, EventArgs e)
        {
            btnOk.Enabled = (dataWorkItem.SelectedRows.Count > 0 || dataWorkItem.SelectedCells.Count > 0);
        }

        private void chkCustomQuery_CheckedChanged(object sender, EventArgs e)
        {
            lblFilterStoredQuery.Enabled = !chkCustomQuery.Checked;
            cboFilterStoredQuery.Enabled = !chkCustomQuery.Checked;
            grpCustomQuery.Enabled = chkCustomQuery.Checked;

            if (chkCustomQuery.Checked)
            {
                FeedCustomQueryField();
            }
        }

        private void FeedCustomQueryField()
        {
            FeedIterationField();
            FeedUserFileds();
        }

        private void FeedIterationField()
        {
            cboFilterCustomIteration.Items.Clear();
            cboFilterCustomIteration.Items.AddRange(m_tfsp.GetIterationList(true).ToArray());
        }

        private void FeedUserFileds()
        {
            cboFilterCustomAssignedTo.Items.Clear();
            cboFilterCustomCreatedBy.Items.Clear();

            cboFilterCustomCreatedBy.Items.AddRange(m_tfsp.GetFieldValues("Task", "Assigned To", true).ToArray());
            cboFilterCustomAssignedTo.Items.AddRange(m_tfsp.GetFieldValues("Task", "Assigned To", true).ToArray());
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewCell dgvc in dataWorkItem.SelectedCells)
            {
                dgvc.OwningRow.Selected = true;
            }
        }

        private void dataWorkItem_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            DataGridView grid = sender as DataGridView;

            if (grid.CurrentCell.OwningColumn.DataPropertyName == "State")
            {
                grid.CurrentCell.Value = grid.CurrentCell.EditedFormattedValue;
            }
        }
    }
}
